const SystemUtils = require("./SystemUtils")
const {pub_length,sign_length} = require('./Contants')
const CryptoUtils = require("./CryptoUtils");

function LicUtils(){}

/**
 * 获取机器信息
 * @param code
 * @returns {string}
 */
function getLicModel(code){
    let model = {
        code:code,
        macAddress:SystemUtils.getMac(),
        cpuSerial:SystemUtils.getCPUMD5(),
        mainBoardSerial:SystemUtils.getMachineId()
    }
    return JSON.stringify(model);
}

/**
 * 校验授权
 */
function verify(ciphertext){
    let pub = ciphertext.substring(0,pub_length);
    let sign = ciphertext.substring(pub_length,pub_length+sign_length);
    let pubstr = '-----BEGIN PUBLIC KEY-----'+pub+'-----END PUBLIC KEY-----'
    let isVerified = CryptoUtils.verifyBySHA256WithRSA(pubstr,sign,pub)
    if(!isVerified){
        return null;
    }

    let cipher = ciphertext.substring(pub_length+sign_length);
    let plainText = CryptoUtils.decryptByRSAPub(pubstr,cipher)

    let model = JSON.parse(plainText);

    //检验是否本机 - 只要最优MAC地址存在即通过
    let macs = SystemUtils.getMac()
    if(model.macAddress.indexOf(macs[0])<0){
        return null;
    }
    let cpu = SystemUtils.getCPUMD5();
    if(model.cpuSerial!==cpu){
        return null;
    }
    let mainBoardSerial = SystemUtils.getMachineId();
    if(model.mainBoardSerial!==mainBoardSerial){
        return null;
    }

    //检验过期时间
    let curr = new Date().getTime()
    if(curr>parseInt(model.expireDate)){
        return null;
    }

    return model;
}

if (typeof LicUtils !== 'undefined') {
    LicUtils.getLicModel = getLicModel;
    LicUtils.verify = verify;
}

module.exports = LicUtils